package com.twittex.view
{
	import com.twittex.TwittexFacade;
	import com.twittex.model.LoginProxy;
	import com.twittex.model.StatusProxy;
	import com.twittex.model.UserProxy;
	import com.twittex.view.components.LoginScreen;
	
	import flash.events.Event;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;

    public class LoginScreenMediator extends Mediator
    {
        public static const NAME:String = "LoginScreenMediator";
        
        private var loginProxy:LoginProxy;


        public function LoginScreenMediator( viewComponent:LoginScreen ) {
            super( NAME, viewComponent );
			
			loginScreen.addEventListener(LoginScreen.LOGIN, onLogin);
        }
        
		/**
		 * Retrieves saved session data
		 */
        override public function onRegister():void {
			loginProxy = facade.retrieveProxy( LoginProxy.NAME ) as LoginProxy;
			loginScreen.loginVO = loginProxy.loginVO;
        }

        override public function listNotificationInterests():Array {
            return [ 
					TwittexFacade.LOGIN_SUCCEED,
					TwittexFacade.LOGIN_FAILED
					];
        }

        override public function handleNotification( note:INotification ):void {
            switch ( note.getName() ) {
				case TwittexFacade.LOGIN_SUCCEED:
					// Register proxies
            		facade.registerProxy(new UserProxy(null, note.getBody()))
					facade.registerProxy(new StatusProxy());

					loginScreen.status = LoginScreen.LOGGED_IN;
					sendNotification(TwittexFacade.VIEW_MAIN_SCREEN);
					break;
				case TwittexFacade.LOGIN_FAILED:
					loginScreen.status = LoginScreen.LOGGIN_ERROR;
					break;
            }
            
            loginScreen.isLogging = false;
        }

        protected function get loginScreen():LoginScreen {
            return viewComponent as LoginScreen;
        }

		private function onLogin(event:Event):void {
			loginScreen.isLogging = true;
			loginScreen.status = LoginScreen.LOGGIN_IN;
			loginProxy.login(loginScreen.loginVO);
		}
		
    }
}
